package com.zg.ktcomwan.data

import com.google.gson.GsonBuilder
import com.google.gson.annotations.JsonAdapter
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import com.squareup.moshi.Moshi
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.concurrent.TimeUnit

/***
 * @Author:      zxd
 * @CreateDate:  2021/6/3 11:04
 * @Description:
 */
object RetrofitUtils {
    val okHttpBuilder: OkHttpClient.Builder
        get() {
            val httpClient = OkHttpClient.Builder()
                .addInterceptor(Interceptor { chain ->
                    val original = chain.request()
                    val request = original.newBuilder()
                        .header("Accept", "application/json")
                        .method(original.method, original.body)
                        .build()
                    return@Interceptor chain.proceed(request)
                })
                .readTimeout(30, TimeUnit.SECONDS)
            // log interceptor
            val loggingInterceptor = HttpLoggingInterceptor()
            loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
            httpClient.addInterceptor(loggingInterceptor)
            return httpClient
        }

    // core for controller
    val service: IApiService = create(IApiService::class.java)

    // 创建另外一个service
    val weatherService: IApiService = create(IApiService::class.java)

    lateinit var retrofit: Retrofit

    fun <T> create(serviceClass: Class<T>): T {
        val gson = GsonBuilder()
            .serializeNulls()
            .create()

        // create retrofit
        retrofit = Retrofit.Builder()
//            .addConverterFactory(GsonConverterFactory.create(gson))
//            .addConverterFactory(MoshiConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            // The call adapter handles threads
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
            .baseUrl("https://www.wanandroid.com/") // Put your base URL
            .client(okHttpBuilder.build())
            .build()
        return retrofit.create(serviceClass)
    }
}